<template>
  <div>
      <div class="top" >
          <el-input   style="width: 20%;margin: 10px 10px;" placeholder="请输入新闻标题关键词" prefix-icon="el-icon-search" v-model="name" maxlength="20"></el-input>
          <el-button type="primary" icon="el-icon-search" @click="searchName">搜索</el-button>
          <el-button style="float: right;" type="primary" @click="handleAdd">添加<i class="el-icon-upload el-icon--right"></i></el-button>
      </div>
      <el-table :data="news" height="700" border stripe style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="内容">
                <span>{{ delTag(props.row.content) }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="nid" label="编号" width="100"></el-table-column>
        <el-table-column align="center" prop="title" label="标题" width="300"></el-table-column>
        <el-table-column align="center" prop="data" label="日期" width="100"></el-table-column>
        <!-- <el-table-column align="center" prop="content" label="内容" width="300"></el-table-column> -->
        <el-table-column align="center" prop="img" label="封面" width="300">
          <template  slot-scope="{ row }">
            <img  style="width: 300px;height: 200px" :src="row.img" alt=""  />
          </template>
        </el-table-column>


        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit"  @click="handleUpdata(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete"  @click="handleDel(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog :visible.sync="addVisible" :modal-append-to-body="false" width="60%" top="0" title="新增" :before-close="Close" >
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="标题" prop="title">
              <el-input  v-model="ruleForm.title" ></el-input>
            </el-form-item>
            <el-form-item label="日期" prop="data">
              <el-date-picker v-model="ruleForm.data" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="封面" prop="img">
              <el-upload class="avatar-uploader" action="http://127.0.0.1:3000/v1/upload/upload" :show-file-list="false" :on-success="handleAvatarSuccess"  >
                <img  v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="内容" prop="content">
              <editor-bar :catchData="catchData"  v-model="ruleForm.content"  ></editor-bar>  
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addReset('ruleForm')">重置</el-button>
          <el-button type="primary" @click=" add('ruleForm')">提交</el-button>
        </span>
      </el-dialog>
      <el-dialog :visible.sync="updataVisible" :modal-append-to-body="false" width="60%" top="0" title="修改" :before-close="Close" >
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="标题" prop="title">
              <el-input  v-model="ruleForm.title" ></el-input>
            </el-form-item>
            <el-form-item label="日期" prop="data">
              <el-date-picker v-model="ruleForm.data" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="封面" prop="img">
              <el-upload class="avatar-uploader" action="http://127.0.0.1:3000/v1/upload/upload" :show-file-list="false" :on-success="handleAvatarSuccess"  >
                <img  v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="内容" prop="content">
              <editor-bar :catchData="catchData"  v-model="ruleForm.content" >
              </editor-bar>  
            </el-form-item>
            
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="updataReset('ruleForm')">重置</el-button>
          <el-button type="primary" @click=" updata('ruleForm')">提交</el-button>
        </span>
      </el-dialog>
  </div>

</template>

<script>
 import EditorBar from "@/components/editoritem.vue"
import myaxios from '../http/MyAxios'
import { BASE_URL } from '@/config'
  export default {
    components: { EditorBar} ,
    data() {
      
      return {
        value:'',
        imageUrl: '',
        news:[],
        nid:0,
        name:'',
        addVisible: false,
        updataVisible:false,
        form:[],
        ruleForm: {
          title:'',
          nid: '',
          data:'',
          content:'',
          img:''
        },
        rules:{
          title:[
          {required:true,message:'该字段必填',trigger:'blur'},
          ],
          data:[
            {required:true,message:'该字段必填',trigger:'blur'},    
          ],
          content:[
          {required:true,message:'该字段必填',trigger:'blur'},
          ],
          img:[
          {required:true,message:'该字段必填',trigger:'blur'},
          ],
        
        }
      }
    },
    beforeMount(){
      this.getNews()
    },
    methods: {

             // 监听富文本的输入
       catchData(e) {
        this.ruleForm.content = e       
      },


      handleAvatarSuccess(res) {
        this.imageUrl = res.result;

      },
      //移除HTML标签
      delTag(str){
      return str.replace(/<[^>]+>/g,"").replace(/&nbsp;/g, "  ");

      },

      updataReset(formName) {
        this.$refs[formName].resetFields();
        this.ruleForm = {}
        this.imageUrl = ''

      },
      updata(formName){

        this.$refs[formName].validate((valid) => {
          if (valid) {
          this.form.nid = this.nid
           this.form.title =  this.ruleForm.title
           this.form.data =  this.ruleForm.data
           this.form.content =  this.ruleForm.content
           this.form.img =  this.imageUrl
            let url=BASE_URL + '/v1/news/allUpdate'
              myaxios.post(url,this.form).then(()=>{
                this.$message({
                  showClose: true,
                  message: '恭喜你，修改成功',
                  type: 'success'
                });

                this.getNews()
                this.updataVisible = false
                }).catch(err=>{
                    console.warn(err);
                  })
          } else {
            alert('提交失败');
            return false;
          }
        });
      },
      handleUpdata(row){
        this.nid = row.nid
        let url=BASE_URL + '/v1/news/idSearch'
        let params = {nid:this.nid}
        myaxios.get(url,params).then(res=>{
          this.ruleForm = res.data.data[0]
          this.imageUrl = this.ruleForm.img
          this.updataVisible = true
        }).catch(err=>{
          console.warn(err);
        })
      },
      addReset(formName) {
        this.$refs[formName].resetFields();
        this.imageUrl = ''
      },
      //格式时间
      p(m){
	  return m < 9 ? '0'+ m : m
	},
      add(formName) {
        this.ruleForm.img = this.imageUrl
        var s = this.ruleForm.data
        const startDate = s.getFullYear() + '-' + this.p((s.getMonth() + 1)) + '-' + 	this.p(s.getDate())
        this.ruleForm.data = startDate
        this.$refs[formName].validate((valid) => {
          if (valid) {
           this.form.title =  this.ruleForm.title 
           this.form.img =  this.ruleForm.img
           this.form.data =  this.ruleForm.data
           this.form.content =  this.ruleForm.content
            let url=BASE_URL + '/v1/news/allAdd'
              myaxios.post(url,this.form).then(()=>{
                this.$message({
                  showClose: true,
                  message: '恭喜你，提交成功',
                  type: 'success'
                });
                this.getNews()
                this.addVisible = false
                }).catch(err=>{
                    console.warn(err);
                  })
          } else {
            alert('提交失败');
            return false;
          }
        });
      },
      handleAdd(){
        this.ruleForm = {}
        this.imageUrl = ''
        this.addVisible = true
      },
      handleDel(row) {
        this.code = row.code
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let url=BASE_URL + '/v1/news/allDelete'
          let params = {nid:row.nid}
            myaxios.get(url,params).then(()=>{
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                this.getNews()
              }).catch(err=>{
                    console.warn(err);
                 })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      Close(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      searchName(){
        let url=BASE_URL + '/v1/news/FuzzySearch'
        myaxios.get(url,{title:this.name}).then(res=>{
          if (res.data.code == 200){
            this.news = res.data.data
          }else{
            this.$message({
                  showClose: true,
                  message: '查询失败,该关键字新闻不存在',
                 type: 'warning'
                });
          }
        }).catch(()=>{
          this.$message({
                  showClose: true,
                  message: '查询失败',
                  type: 'error'
                });
        })

      },
      getNews(){
        let url=BASE_URL + '/v1/news/allSearch'
        myaxios.get(url).then(res=>{
          this.news = res.data.data
        }).catch(err=>{
          console.warn(err);
        })
    },
    },
  }
</script>
<style scoped lang="scss">
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>